import { SYSTEM_CONFIG } from '@/base/interface-config';
import { useUserStore } from '@/store/user';
import { ElMessage } from 'element-plus';
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';

// 自动导入 views 目录下的所有页面组件
// const modules = import.meta.glob('../views/**/*.vue', { eager: true });
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/normal/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/normal/layout/index.vue'),
    redirect: '/home',
    meta: { title: '首页', icon: 'House' },
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/normal/home/index.vue'),
        children: []
      },
      // 业务系统（business）相关页面
      {
        path: '/',
        name: 'Business',
        children: [
          {
            path: '/base',
            name: 'Base',
            meta: { title: '基础数据', icon: 'Box' },
            children: []
          }
        ]
      },
      // 管理系统（manage）相关页面
      {
        path: '/',
        name: 'Manage',
        children: [
          {
            path: '/system',
            name: 'System',
            meta: { title: '系统管理', icon: 'Monitor' },
            children: [
              {
                path: '/system/dict',
                name: 'Dict',
                component: () => import('@/views/manage/dict/index.vue'),
                meta: { title: '字典管理', icon: 'Document' }
              },
              {
                path: '/system/system-dict',
                name: 'SystemDict',
                component: () => import('@/views/manage/system-dict/index.vue'),
                meta: { title: '系统字典', icon: 'Document' }
              }
            ]
          }
        ]
      }
    ]
  },
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/normal/error/403.vue'),
    meta: { title: '403', hidden: true }
  },
  {
    path: '/500',
    name: '500',
    component: () => import('@/views/normal/error/500.vue'),
    meta: { title: '500', hidden: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/normal/error/404.vue'),
    meta: { title: '404', hidden: true }
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title} - ${SYSTEM_CONFIG.name}`;
  // 设置系统类型: manage/business
  const path = location.href?.match(/\/manage\/|\/business\//)?.[0];
  if (path) {
    localStorage.setItem('systemType', path);
  }

  const token = localStorage.getItem('token');
  // 登录页面特殊处理
  if (to.path === '/login') {
    if (token) {
      next('/');
    } else {
      ElMessage.warning('请先登录');
      next();
    }
    return;
  }

  // 未登录重定向到登录页
  if (!token) {
    next('/login');
    return;
  }

  // 已登录状态下的权限检查
  try {
    const userStore = useUserStore();

    // 如果路由需要权限且用户没有权限
    if (to.meta.permission && !userStore.hasPermission(String(to.meta.permission))) {
      next('/403');
      return;
    }

    next();
  } catch (error) {
    console.error('路由守卫错误:', error);
    next('/500');
  }
});

export default router;
